using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

using Tino.Controls;
using Tino.Core;

namespace Tino
{
    public class GetEntriesCommand : ICommand
    {
        GetEntriesCommandDelegate invokeMe;
        EntriesListBox list;
        int[] tags;

        delegate DataTable GetEntriesCommandDelegate(int[] TagIDs);

        public GetEntriesCommand(EntriesListBox List) : this(List, null) { }

        public GetEntriesCommand(EntriesListBox List, int[] TagIDs)
        {
            list = List;
            tags = TagIDs;

            Entry entry = new Entry();
            invokeMe = new GetEntriesCommandDelegate(entry.GetEntries);
        }

        void Callback(IAsyncResult ar)
        {
            // get the dataset as output
            DataTable dt = invokeMe.EndInvoke(ar);

            // update the grid & the autocompletion collection a thread safe fasion!
            MethodInvoker updateList = delegate
            {
                list.BeginUpdate();
                list.Clear();                
                foreach (DataRow dr in dt.Rows)
                {
                    string t = (string)dr["Title"];
                    int i = Convert.ToInt32(dr["ID"]);
                    int imgIdx = Convert.ToInt32(dr["ImageIndex"]);
                    list.Add(t, i, imgIdx);
                }
                list.EndUpdate();
            };

            if (list.InvokeRequired)
            {
                list.Invoke(updateList);
            }
            else
            {
                updateList();
            }
        }

        #region ICommand Members

        public void Execute()
        {
            invokeMe.BeginInvoke(tags, this.Callback, null);
        }

        #endregion
    }
}
